﻿import { Employee } from './../domain/model/employee';
import { ServiceException } from "./serviceException";
import { MPJRequestManager } from "../common/http/mpjRequest";
let webconfig = require("../../webconfig").webconfig;

export class AuthService {
    async login(storeId: string, account: string, password: string): Promise<{ employee: Employee, token: string }> {
        let url = '/api/stores/' + storeId + '/employees/v2/login';
        let postData = {
            account: account,
            password: password
        }
        let res = await MPJRequestManager.Current.GetMPJRequest().Post<any>(url, postData);
        if (res.result === "FAILED" && res.code === "USER_PASSWD_ERR")
            throw new ServiceException(this, "用户名或密码错误！");
        else if (res.result === "FAILED" && res.code === "NOT_BELONG_TO_SHOP")
            throw new ServiceException(this, "该店员不属于本店铺！");
        else if (res.result === "FAILED" && res.code == "STORE_OVERDUE_ERR") {
            throw new ServiceException(this, "店铺已经过期，请联系客户开通！");
        }
        else if (res.result === "SUCCESS") {
            let hasAuthentication = true;
            if (res.employee.roles) {
                let role = res.employee.roles.find(r => r.name == "owner" || r.name == "cashier" || r.name == "store operator" || r.name == "store manager" || r.name == "waiter");
                hasAuthentication = role;
            }
            else {
                hasAuthentication = false;
            }
            if (!hasAuthentication) throw new ServiceException(this, "权限不够，请联系店面管理者！");

            let result: Employee = new Employee();
            result = result.clone(res.employee, result, false);
            return {
                employee: result,
                token: res.token
            }
        }
    }
}